package com.anpy.bill.controller;

import com.anpy.bill.model.param.AccountLoginParam;
import com.anpy.bill.model.result.LoginResult;
import com.anpy.bill.service.LoginService;
import com.anpy.bill.service.TokenService;
import com.anpy.common.service.model.result.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * @Description: 登录接口
 * @Author: anpy
 * @date: 2025/4/7 15:41
 */
@RestController
@RequestMapping("/login")
@Validated
@Tag(name = "登录接口", description = "提供登录相关功能")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private TokenService tokenService;

    @Operation(summary = "账号密码登录", description = "通过账号密码进行登录认证")
    @PostMapping("/account")
    public ApiResult<LoginResult> loginByAccount(@Valid @RequestBody AccountLoginParam param) {
        return ApiResult.success(loginService.accountLogin(param));
    }

    @Operation(summary = "获取验证码", description = "获取图形验证码")
    @GetMapping("/validCode")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        loginService.getCaptcha(request, response);

    }

    @Operation(summary = "注销登录", description = "注销当前用户登录状态")
    @PostMapping("/logout")
    public ApiResult<Void> logout(HttpServletRequest request) {
        Object userId = request.getAttribute("userId");
        if (userId != null) {
            tokenService.logout(String.valueOf(userId));
        }
        return ApiResult.success();
    }

}
